package im

import (
	"strconv"
	"encoding/json"
	"dhfshop/models/isv"
	"dhfshop/controllers/base"
	"thirdpaysdk/api/wisecashier"
	"github.com/astaxie/beego"
	"dhfshop/domain/im"
	"dhfshop/domain/pay"
	"dhfshop/service/redisgo"
)

type WiseNotifyController struct {
	base.BaseController
}

//wisecashier异步回调
func (this *WiseNotifyController) WisePayNotify() {
	signature := this.Ctx.Input.Header("Signature")
	timeStamp := this.Ctx.Input.Header("Timestamp")
	//beego.Debug("WisePayNotify Signature:", signature)
	//beego.Debug("WisePayNotify Timestamp:", timeStamp)
	//
	var v wisecashier.WisecashierMsg
	this.ParseForm(&v)
	body, err := json.Marshal(v)
	if err == nil {
		beego.Debug("WisePayNotify Body:", string(body))
	}
	var payInfoCache *paylayer.PayInfoCache = new(paylayer.PayInfoCache)
	cacheKey := "payorder_" + v.AgentOrderId
	redisconn := redisgo.GetInstance()
	if cacheValue, err := redisconn.GetString(cacheKey); err == nil && len(cacheValue) > 5  {
	    //beego.Debug("WisePayNotify cache pay info:", cacheValue)
		if err = json.Unmarshal([]byte(cacheValue), payInfoCache); err == nil {
			
		}
	}else{
	    beego.Debug("WisePayNotify cache pay info err:", err.Error())
		return 
	}
	timeStampTmp, _:= strconv.ParseInt(timeStamp, 10, 64)
	acPayParams, err := isv.GetAcPayParamsByMchId(payInfoCache.MchId)
	if err != nil {
		beego.Debug("WisePayNotify GetAcPayParamsByMchId:", err.Error())
		return
	}
	reqMap, err := wisecashier.WisecashierNotify(&v,[]byte(acPayParams.PemCert),[]byte(signature), timeStampTmp)
	if err != nil {
	    beego.Debug("WisecashierNotify err:", err.Error())
		return
	}
	//
	reqMap["LocalKind"] = "WISE_PAY_NOTIFY"
	reqMap["attach"] = payInfoCache.OrderKind
	reqMap["currency"] = v.Currency
	imlayer.PushMsgSvrIns.PushDao <- &reqMap
	this.Ctx.WriteString("success")
	return
}
